package com.bw.z.mvp.view.news;

import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.bw.z.App;
import com.bw.z.R;
import com.bw.z.db.UserTable;
import com.bw.z.mvp.HttpCode;
import com.bw.z.mvp.base.view.BaseActivity;
import com.bw.z.mvp.contract.NewsContract;
import com.bw.z.mvp.di.DaggerNewsComponent;
import com.bw.z.mvp.di.NewsModules;
import com.bw.z.mvp.model.entity.BaseEntity;
import com.bw.z.mvp.model.entity.ChannelEntity;
import com.bw.z.mvp.model.entity.LocalChannel;
import com.bw.z.mvp.model.entity.MoreChannel;
import com.bw.z.mvp.presenter.NewsPresenter;
import com.bw.z.mvp.view.news.adapter.BaseUserChannelAdapter;
import com.bw.z.mvp.view.news.adapter.CommentAdapter;
import com.bw.z.mvp.view.news.adapter.LocalChannelAdapter;
import com.bw.z.mvp.view.news.adapter.MoreChannelAdapter;
import com.bw.z.mvp.view.news.adapter.UserChannelAdapter;
import com.bw.z.utils.LogUtils;
import com.bw.z.utils.SpUtils;
import com.bw.z.utils.ToastUtils;
import com.bw.z.widget.ChannelItemDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.cyan.dragrecyclerview.DragRecyclerView;
import cn.cyan.dragrecyclerview.HoldTouchHelper;

public class ChannelActivity extends BaseActivity<NewsPresenter>
        implements NewsContract.NewView, HoldTouchHelper.OnItemTouchEvent,
        View.OnClickListener, OnItemClickListener {

    private android.widget.LinearLayout channelRoot;
    private android.widget.ImageView channelBackImg;
    private cn.cyan.dragrecyclerview.DragRecyclerView channelDragRv;
    private View view_channel_head;
    private View view_channel_local;
    private View view_channel_more;
    private View view_channel_user;
    private View view_channel_foot_local;
    private View view_channel_foot_more;
    private RecyclerView channel_foot_local_rv;
    private RecyclerView channel_more_rv;
    private TextView channel_user_edt_tv;
    private UserChannelAdapter channelAdapter;
    private LocalChannelAdapter localChannelAdapter;
    private MoreChannelAdapter moreChannelAdapter;
    private boolean edtFlag = false;//false状态时频道不可编辑，true可编辑

    @Override
    public View addStatusView() {
        return f(R.id.channel_root);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_channel;
    }

    @Override
    public void initView() {
        getColors(Color.WHITE);
        channelRoot = (LinearLayout) findViewById(R.id.channel_root);
        channelBackImg = (ImageView) findViewById(R.id.channel_back_img);
        channelDragRv = (DragRecyclerView) findViewById(R.id.channel_drag_rv);
        view_channel_head = LayoutInflater.from(this).inflate(R.layout.view_channel_head, null);
        view_channel_user = LayoutInflater.from(this).inflate(R.layout.view_channel_user, null);
        view_channel_local = LayoutInflater.from(this).inflate(R.layout.view_channel_local, null);
        view_channel_more = LayoutInflater.from(this).inflate(R.layout.view_channel_more, null);
        view_channel_foot_local = LayoutInflater.from(this).inflate(R.layout.view_channel_foot_local, null);
        view_channel_foot_more = LayoutInflater.from(this).inflate(R.layout.view_channel_foot_more, null);
        channel_user_edt_tv = view_channel_user.findViewById(R.id.channel_user_edt_tv);
        channel_foot_local_rv = view_channel_foot_local.findViewById(R.id.channel_foot_local_rv);
        channel_more_rv = view_channel_foot_more.findViewById(R.id.channel_more_rv);
        GridLayoutManager userManager = new GridLayoutManager(this, 4);
        userManager.setOrientation(GridLayoutManager.VERTICAL);
        GridLayoutManager moreManager = new GridLayoutManager(this, 4);
        moreManager.setOrientation(GridLayoutManager.VERTICAL);
        GridLayoutManager lcoalManager = new GridLayoutManager(this, 4);
        lcoalManager.setOrientation(GridLayoutManager.VERTICAL);
        channel_foot_local_rv.setLayoutManager(lcoalManager);
        channel_more_rv.setLayoutManager(moreManager);
        channelDragRv.setLayoutManager(userManager);
        channel_more_rv.addItemDecoration(new ChannelItemDecoration(this));
        channelDragRv.addItemDecoration(new ChannelItemDecoration(this));
        channel_foot_local_rv.addItemDecoration(new ChannelItemDecoration(this));
        localChannelAdapter = new LocalChannelAdapter();
        moreChannelAdapter = new MoreChannelAdapter();
        moreChannelAdapter.setOnItemClickListener(this);
        localChannelAdapter.setOnItemClickListener(this);
        channel_foot_local_rv.setAdapter(localChannelAdapter);
        channel_more_rv.setAdapter(moreChannelAdapter);
        channelAdapter = new UserChannelAdapter();
        channelAdapter.addHeaderView(view_channel_head, 0);
        channelAdapter.addHeaderView(view_channel_user, 1);
        channelAdapter.addFooterView(view_channel_more, 0);
        channelAdapter.addFooterView(view_channel_foot_more, 1);
        channelAdapter.addFooterView(view_channel_local, 2);
        channelAdapter.addFooterView(view_channel_foot_local, 3);
        channelDragRv.setDragAdapter(channelAdapter)
                .dragEnable(true)
                .showDragAnimation(true)
                .bindEvent(this);
        channelBackImg.setOnClickListener(this::onClick);
        channel_user_edt_tv.setOnClickListener(this::onClick);
        channelAdapter.setOnItemClickListener(this::onItemClick);
    }

    @Override
    public void inject() {
        DaggerNewsComponent.builder().newsModules(new NewsModules(this)).build().injectChannelNews(this);
    }

    @Override
    public void initData() {
        Long id = SpUtils.readDataLong("user_id");
        LogUtils.show("ZLQ id:" + id);
        int user_id = 1;
        if (id != 0l)
            user_id = App.dbManager.getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id")).getUser_id();
        LogUtils.show("user_id:" + user_id);
        //我的频道
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("code", HttpCode.USERCHANNELCODE);
        userMap.put("imie", "");
        userMap.put("userId", user_id);
        //更多频道
        Map<String, Object> moreMap = new HashMap<>();
        moreMap.put("code", HttpCode.MORECHANNELCODE);
        moreMap.put("imie", "");
        moreMap.put("userId", user_id);
        //地方频道
        Map<String, Object> localMap = new HashMap<>();
        localMap.put("code", HttpCode.LOCALCHANNELCODE);
        localMap.put("imie", "");
        localMap.put("userId", user_id);
        p.requestAll(localMap, moreMap, userMap);
    }

    @Override
    public void refreshAll(BaseEntity baseEntity) {
        com.blankj.utilcode.util.LogUtils.json(baseEntity);
        if (baseEntity instanceof ChannelEntity) {
            ChannelEntity channelEntity = (ChannelEntity) baseEntity;
            //我的频道接口返回值
            channelAdapter.setNewInstance(channelEntity.getValues());
        } else if (baseEntity instanceof LocalChannel) {
            LocalChannel localChannel = (LocalChannel) baseEntity;
            //本地频道接口返回值
            localChannelAdapter.setNewInstance(localChannel.getValues());
        } else if (baseEntity instanceof MoreChannel) {
            //更多频道接口返回值
            MoreChannel moreChannel = (MoreChannel) baseEntity;
            moreChannelAdapter.setNewInstance(moreChannel.getValues());
        } else {
            //收藏频道接口返回值
            if (baseEntity.status.equals("200")) {
                //保存界面数据成功
                //通知newsFragment更新频道数据
            }
        }
    }

    @Override
    public void refreshRecyclerView(BaseEntity baseEntity) {

    }

    @Override
    public void loadMoreRecyclerView(BaseEntity baseEntity) {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.channel_back_img == id) {
            finish();
        } else if (R.id.channel_user_edt_tv == id) {
            String str = channel_user_edt_tv.getText().toString();
            if (str.equals("编辑")) {
                channel_user_edt_tv.setText("完成");
                //我的频道可拖动,地方以及更多频道可通过item点击添加到我的频道中
                edtFlag = true;
            } else {
                channel_user_edt_tv.setText("编辑");
                edtFlag = false;
                Intent intent = new Intent();
                intent.setAction("newsTab");
//                sendBroadcast(intent);
                //发起网络请求保存用户最新收藏的频道
                updateChannel();
            }
        }
    }

    private void updateChannel() {
        UserTable userTable = App.dbManager.getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id"));
        int user_id = userTable.getUser_id();
        List<Map<String, Object>> channels = new ArrayList<>();
        List<ChannelEntity.Values> datas = channelAdapter.getData();
        for (int i = 0; i < datas.size(); i++) {
            ChannelEntity.Values values = datas.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("channel_id", values.channel_id);
            channels.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.COLLECTIONCHANNELCODE);
        map.put("imie", "");
        map.put("user_id", user_id);
        map.put("channeles", channels);
        p.requestAll(map);
//        channelAdapter.getData().clear();
    }

    @Override
    public void onLongPress(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int position) {
        if (!edtFlag) {
            return;
        }
        if (((BaseUserChannelAdapter) recyclerView.getAdapter()).onItemDrag(position)) {
            ((DragRecyclerView) recyclerView).startDrag(position);
        }
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int position) {

    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof UserChannelAdapter) {
            //我的
            ChannelEntity.Values entity = channelAdapter.getItem(position);
            MoreChannel.Values values = new MoreChannel.Values();
            values.channel_hot = entity.channel_hot;
            values.channel_id = entity.channel_id;
            values.channel_name = entity.channel_name;
            moreChannelAdapter.addData(values);
            channelAdapter.remove(entity);
        }
        if (!edtFlag) {
            return;
        }
        //区分对应哪个Adapter被点击local more
        if (adapter instanceof LocalChannelAdapter) {
            //本地
            LocalChannel.Values entity = localChannelAdapter.getItem(position);
            ChannelEntity.Values values = new ChannelEntity.Values();
            values.dropEnable = true;
            values.dragEnable = true;
            values.channel_hot = entity.channel_hot;
            values.channel_id = entity.channel_id;
            values.channel_name = entity.channel_name;
            channelAdapter.addData(values);
            localChannelAdapter.remove(entity);
        } else {
            //更多
            MoreChannel.Values entity = moreChannelAdapter.getItem(position);
            ChannelEntity.Values values = new ChannelEntity.Values();
            values.dropEnable = true;
            values.dragEnable = true;
            values.channel_hot = entity.channel_hot;
            values.channel_id = entity.channel_id;
            values.channel_name = entity.channel_name;
            channelAdapter.addData(values);
            moreChannelAdapter.remove(entity);
        }

    }
}